package cardutil

import (
	"bufio"
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

func ReplaceCardNameByText(cardDirPath string, nameTexPath string, split string,
	dealMapId func(mapId string) string, dealMapName func(mapName string) string, dealPicName func(picName string) string) {

	if dealMapId == nil {
		dealMapId = func(mapId string) string {
			return mapId
		}
	}
	if dealMapId == nil {
		dealMapId = func(mapId string) string {
			return mapId
		}
	}

	nameText, _ := os.Open(nameTexPath)
	defer nameText.Close()
	reader := bufio.NewReader(nameText)
	nameMap := make(map[string]string)
	for true {
		line, _, _ := reader.ReadLine()
		if len(line) == 0 {
			break
		}
		nameIndex := bytes.IndexAny(line, split)

		nameMap[dealStringByFun(string(line[0:nameIndex]), dealMapId)] = strings.NewReplacer("/", "／", "?", "？").Replace(dealStringByFun(string(line[nameIndex+3:]), dealMapName))
	}
	replaceName(nameMap, cardDirPath, dealPicName)
}

func dealStringByFun(str string, deal func(s string) string) string {
	if deal == nil {
		return str
	} else {
		return deal(str)
	}
}

func replaceName(nameMap map[string]string, cardDirPath string, dealPicName func(picName string) string) {

	if dealPicName == nil {
		dealPicName = func(picName string) string {
			return picName
		}
	}

	//_ = filepath.Walk(cardDirPath, func(path string, info os.FileInfo, _ error) error {
	//
	//
	//})

	cardDir, _ := ioutil.ReadDir(cardDirPath)
	for _, card := range cardDir {
		cardName0 := card.Name()
		i := strings.LastIndexByte(cardName0, '.')
		ex := cardName0[i:]
		id := dealStringByFun(cardName0[0:i], dealPicName)
		cardName := nameMap[id]
		if cardName == "" {
			fmt.Println("map内没有该id： " + id)
			return
		}
		_ = os.Rename(cardDirPath+cardName0, cardDirPath+cardName+ex)
		fmt.Println(cardName0 + " 被重命名为 " + cardName)
	}

}
